/*
 * TcpConnection.h
 *
 *  Created on: Jul 26, 2016
 *      Author: Lucifer
 */

#ifndef BFX_TCPCLIENT_H_
#define BFX_TCPCLIENT_H_

#include "./Socket.h"
#include "./Selector.h"

namespace BFX {

class TcpClient: public RCObject {
public:
	typedef void (*ClientCallback)(TcpClient* client);

	TcpClient();
	TcpClient(Socket* socket);
	virtual ~TcpClient();

	bool isConnected() const {
		return _connected;
	}
	bool connect(InetAddress* addr);

	bool start(Selector* sel, ClientCallback callback);
	void stop();

	/// Tests whether this key's channel is ready for reading.
	bool isReadable() const {
		return !!(_curReadyOps & SelectionKey::OP_READ);
	}
	/// Tests whether this key's channel is ready for writing.
	bool isWritable() const {
		return !!(_curReadyOps & SelectionKey::OP_WRITE);
	}
	/// Tests whether this key's channel has either finished.
	bool isConnectable() const {
		return !!(_curReadyOps & SelectionKey::OP_CONNECT);
	}

private:
	static void eventCallback(SelectionKey* key);

private:
	REF<SelectableChannel> _channel;
	bool _active;
	bool _connected;
	ClientCallback _callback;
	mutable int _curReadyOps;
};

} /* namespace BFX */

#endif /* BFX_TCPCLIENT_H_ */
